using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using NerdDinner.Web.Models.Repository;
using NerdDinner.Web.Models.Data;
using NerdDinner.Web.Helpers;
using NerdDinner.Web.Models;
using NerdDinner.Web.Models.ViewData;
using NerdDinner.Web.Models.Validation;

namespace NerdDinner.Web.Controllers
{
    [HandleElmahError]
    public class DinnersController : Controller
    {
        private IDinnerRepository _repository;

        public DinnersController() : this(new DinnerRepository()) { }

        public DinnersController(IDinnerRepository repository)
        {
            _repository = repository;
        }

        //
        // HTTP-GET: /Dinners/

        public ActionResult Index()
        {
            ViewData["PageTitle"] = "Find a Dinner";

            return View("Index");
        }

        //
        // HTTP-GET: /Dinners/All

        public ActionResult Paged( int? page )
        {
            ViewData["PageTitle"] = "All Dinners";

            const int pageSize = 5;
            var allDinners = _repository.FindAllDinners();
            var allPaginatedDinners = new PaginatedList<Dinner>( allDinners, (page ?? 0), pageSize );

            return View("Paged", allPaginatedDinners);
        }

        public ActionResult All()
        {
            ViewData["PageTitle"] = "All Dinners";

            var allDinners = _repository.FindAllDinners();

            return View("All", allDinners);
        }

        //
        // HTTP-GET: /Dinners/Upcoming

        public ActionResult Upcoming()
        {
            ViewData["PageTitle"] = "Upcoming Dinners";

            var upcomingDinners = _repository.FindUpcomingDinners();

            return View( "Upcoming", upcomingDinners );
        }

        //
        // HTTP-GET: /Dinners/Details/2

        public ActionResult Details( int number )
        {
            ViewData["PageTitle"] = "Details";
            var model = _repository.GetDinner(number);

            if (model == null)
                return View( "NotFound" );
            else
                return View( "Details", model );
        }

        //
        // HTTP-GET: /Dinners/Edit/2

        public ActionResult Edit(int number)
        {
            var dinner = _repository.GetDinner(number);
            //ViewData["Countries"] = new SelectList(PhoneValidator.Countries, dinner.Country);

            if (!dinner.IsHostedBy(User.Identity.Name))
                return View("InvalidOwner");

            if (dinner == null)
                return View("NotFound");

            ViewData["username"] = User.Identity.Name;

            return View("Edit", new DinnerFormViewModel(dinner));
        }

        //
        // HTTP-POST: /Dinners/Edit/2

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit( int number, Dinner whatever )
        {
            Dinner dinner = _repository.GetDinner(number);

            if (!dinner.IsHostedBy(User.Identity.Name))
                return View("InvalidOwner");

            try
            {
                UpdateModel(dinner);
                _repository.Save();
                return RedirectToAction("Details", new { number = dinner.DinnerId });
            }
            catch (Exception)
            {
                //foreach (var issue in dinner.GetRuleViolations()) 
                //{ 
                //    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage); 
                //}

                ModelState.AddRuleViolations(dinner.GetRuleViolations());
                ViewData["Countries"] = new SelectList(PhoneValidator.Countries, dinner.Country);
                return View("Edit",new DinnerFormViewModel(dinner));
            }
            
        }

        //
        //GET: /Dinners/Create

        [Authorize]
        public ActionResult Create()
        {
            Dinner dinner = new Dinner();
            dinner.EventDate = DateTime.Now.AddDays(7);
            return View("Create", new DinnerFormViewModel(dinner));
        }

        //
        //POST: /Dinners/Create

        [AcceptVerbs(HttpVerbs.Post),Authorize]
        public ActionResult Create(Dinner dinner)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    dinner.HostedBy = User.Identity.Name;

                    RSVP rsvp = new RSVP();
                    rsvp.AttendeeName = User.Identity.Name;
                    dinner.RSVPs.Add(rsvp); 

                    _repository.Add(dinner);
                    _repository.Save();
                    return RedirectToAction("Details", new { number = dinner.DinnerId });
                }
                catch (Exception)
                {
                    ModelState.AddRuleViolations(dinner.GetRuleViolations());
                }
            }
            return View("Create", new DinnerFormViewModel(dinner));
        }

        //
        //GET: /Dinners/Delete/1

        public ActionResult Delete(int number)
        {
            var dinner = _repository.GetDinner(number);

            if (!dinner.IsHostedBy(User.Identity.Name))
                return View("InvalidOwner");

            if (dinner == null)
                return View("NotFound");
            else
                return View("Delete", dinner);

        }

        //  
        // HTTP POST: /Dinners/Delete/1 
         
        [AcceptVerbs(HttpVerbs.Post)] 
        public ActionResult Delete(int number, string confirmButton) 
        {
            Dinner dinner = _repository.GetDinner(number);

            if (!dinner.IsHostedBy(User.Identity.Name))
                return View("InvalidOwner");

            if (dinner == null) 
                return View("NotFound");

            _repository.Delete(dinner);
            _repository.Save(); 
              
            return View("Deleted"); 
        } 
    }
}
